
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jl_plugin/bean/BlueDevice.dart';
import 'package:jl_plugin/callback/BtRcspCallBack.dart';
import 'package:jl_plugin/contain/StateCode.dart';
import 'package:jl_plugin/contain/NotifyAdvInfoCmd.dart';
import 'package:jl_plugin/jl_plugin.dart';
import 'package:jl_plugin/contain/Command.dart';
import 'package:jl_plugin_example/AppBarLeftTitle.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:jl_plugin_example/BlueCmdPage.dart';
import 'package:jl_plugin_example/BlueEqSettingPage.dart';
import 'package:jl_plugin_example/BlueKeySettingPage.dart';
import 'package:jl_plugin_example/BlueRecordPage.dart';
import 'package:jl_plugin_example/widget/AppColors.dart';
import 'package:jl_plugin_example/widget/MyTextField.dart';
import 'package:jl_plugin_example/widget/TextUtils.dart';


class BlueDetailPage extends StatefulWidget{
  BlueDevice blueDevice;

  BlueDetailPage(this.blueDevice);

  @override
  State<StatefulWidget> createState() {
    return _State();
  }
}

class _State extends State<BlueDetailPage> implements BtRcspCallBack{
  late BlueDevice blueDevice;
  int leftDeviceQuantity=0;
  int rightDeviceQuantity=0;
  String deviceInfo="";
  @override
  void initState() {
    super.initState();
    blueDevice=widget.blueDevice;
    deviceNameEditor.text=blueDevice.name;
    JlPlugin.instance.addBtCallback(this);
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff6f6f6),
      appBar: AppBarLeftTitle(title: widget.blueDevice.name),
      body: Container(
        padding: EdgeInsets.all(16),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(mainAxisAlignment: MainAxisAlignment.start,children: [
                Expanded(
                  child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: [
                    Text("设备名字:${blueDevice.name}"),
                    Text("设备地址:${blueDevice.address}"),
                  ],),
                ),
                TextButton(onPressed: (){
                  clickConnect();
                }, child: Text(getConnectStatusText()))
              ],),
              Visibility( visible: blueDevice.connectStatus==StateCode.CONNECTION_OK,child: changeDeviceName()),
              Visibility(
                visible: blueDevice.connectStatus==StateCode.CONNECTION_OK,
                child: Wrap(
                  alignment: WrapAlignment.start, // ⬅️ 左对齐
                  spacing: 8.0,
                  runSpacing: 4.0
                  ,direction: Axis.horizontal,children: [
                  TextButton(onPressed: (){
                    intentRecord();
                  }, child: Text("录音功能")),
                  TextButton(onPressed: (){
                    getKeySetting();
                  }, child: Text("设备信息")),
                  TextButton(onPressed: (){
                    Navigator.push(context, MaterialPageRoute(builder: (context)=>BlueEqSettingPage(widget.blueDevice)));
                  }, child: Text("eq设置")),
                  TextButton(onPressed: (){
                    Navigator.push(context, MaterialPageRoute(builder: (context)=>BlueCmdPage(widget.blueDevice)));
                  }, child: Text("发送指令")),
                  TextButton(onPressed: (){
                    Navigator.push(context, MaterialPageRoute(builder: (context)=>BlueKeySettingPage()));
                  }, child: Text("按键设置")),
                  TextButton(onPressed: (){
                    JlPlugin.instance.getHistoryBluetoothDeviceList().then((value){
                      print("设备：--${value}");
                    });
                  }, child: Text("获取历史设备")),
                ],),
              ),
             Visibility(visible: blueDevice.connectStatus==StateCode.CONNECTION_OK,
             child: Column(children: [
               SizedBox(height: 20),
               Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly,children: [
                 Text("左耳电量:${leftDeviceQuantity}%"),
                 Text("左耳电量:${rightDeviceQuantity}%"),
               ],),
               SizedBox(height: 10),

               Container(
                   width: double.infinity,
                   padding: EdgeInsets.all(6),
                   constraints: BoxConstraints(
                       minHeight: 120
                   ),
                   decoration: BoxDecoration(
                       borderRadius: BorderRadius.circular(12),
                       border: Border.all(color: Color(0xff999999),width: 1)
                   ),
                   child: SelectableText(deviceInfo,style: TextStyle(color: Color(0xff333333),fontSize: 13),)),
               SizedBox(height: 10),

               SizedBox(height: 20),

             ],),)
            ],
          ),
        ),
      ),
    );
  }

  TextEditingController deviceNameEditor=TextEditingController();
  Widget changeDeviceName(){
    return Container(
      margin: EdgeInsets.symmetric(vertical: 15),
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
        border: Border.all(color: c_999999,width: 1),
        borderRadius: BorderRadius.circular(12)
      ),
      child: Row(children: [
        Expanded(child: MyTextField(controller: deviceNameEditor,hintText: "修改设备名字")),
        SizedBox(width: 10),
        TextButton(onPressed: () async{
          if(TextUtils.isNotEmpty(deviceNameEditor.text)){
           var result=await JlPlugin.instance.changeDeviceName(deviceNameEditor.text);
           print("changeDeviceName->${result}");
           if(result.code==1){
             SmartDialog.showToast("重启设备中");
             var rebootDeviceResult=await JlPlugin.instance.rebootDevice();
             print("rebootDeviceResult->${rebootDeviceResult}");
           }

          }
        }, child: Text("修改设备名"))
      ]),
    );
  }


  String getConnectStatusText(){
    if(blueDevice.connectStatus==StateCode.CONNECTION_CONNECTING){
      return "连接中";
    }else if(blueDevice.connectStatus==StateCode.CONNECTION_OK){
      return "断开";
    }else{
      return "连接";
    }
  }

  void clickConnect(){
    if(blueDevice.connectStatus==StateCode.CONNECTION_OK){
      //断开
      JlPlugin.instance.disconnectBlue(blueDevice);
    }else if(blueDevice.connectStatus==StateCode.CONNECTION_CONNECTING){
      SmartDialog.showToast("设备连接中");
    }else{
      JlPlugin.instance.connectBlue(blueDevice);
    }
  }

  void getKeySetting(){
    JlPlugin.instance.deviceSettingInfo(0xffffffff, successCall: (info){
      print("device Info:${info.toJson()}");
      setState(() {
        deviceInfo=jsonEncode(info.toJson());
      });
    }, onErrorCall: (errorResult){
      print("device onErrorCall:${errorResult.toString()}");
    });
  }

  void intentRecord(){
    Navigator.push(context, MaterialPageRoute(builder: (context)=>BlueRecordPage()));
  }


  @override
  void dispose() {
    super.dispose();
    JlPlugin.instance.disconnectBlue(widget.blueDevice);
    JlPlugin.instance.removeBtCallback(this);
  }

  @override
  void onBondStatus(BlueDevice device) {
  }

  @override
  void onConnected(BlueDevice device) {
    if(device.connectStatus==StateCode.CONNECTION_CONNECTING){
      //连接中 显示dialog
      SmartDialog.showLoading(msg: "设备连接中");
    }else{
      //隐藏dialog
      SmartDialog.dismiss();
      if(device.connectStatus==StateCode.CONNECTION_OK){
        //连接成功
      }
    }
    setState(() {
      blueDevice=device;
      blueDevice.connectStatus=device.connectStatus;
    });
  }

  @override
  void onDeviceCommand(BlueDevice device) {
    var cmID=device.cmdParam["opCode"];
    print("指令:${cmID}");
    if(cmID==Command.CMD_ADV_DEVICE_NOTIFY){
      var notifyBean=NotifyAdvInfoCmd.fromMap(device.cmdParam);
      leftDeviceQuantity=notifyBean.param.leftDeviceQuantity;
      rightDeviceQuantity=notifyBean.param.rightDeviceQuantity;
      if(mounted){
        setState(() {

        });
      }

    }
  }
}